<?php
echo "master:" . posix_getpid() . PHP_EOL;
$childs = [];
function fork()
{
    global $childs;
    $pid = pcntl_fork();
    if ($pid < 0) die("fork err");
    if ($pid == 0) {
        $child_pid = posix_getpid();
        echo 'child=' . $child_pid . PHP_EOL;
        while (true) {
            sleep(10);
        }

    } else {
        $parent_pid = posix_getpid();
        $childs[$pid] = $pid;


    }
}

$worker_num = 3;
for ($i = 0; $i < $worker_num; $i++) {
    fork();
}
while (count($childs)) {
    if (($exit_id = pcntl_wait($status)) > 0) {
        $signo = pcntl_wtermsig($status);
        echo "child [{$exit_id}]  receive {$signo} exited!" . PHP_EOL;
        unset($childs[$exit_id]);
    }
    if (count($childs) < $childs) {
        fork();
    }
}

echo "end!" . PHP_EOL;

